<script lang="ts" setup>

const { t, locale } = useI18n();
import { useForm } from 'vee-validate';
import * as yup from 'yup';
defineOptions({
  name: 'BindAccount',
})

definePageMeta({
    layout: 'header-back',
    title: 'account_management'
})
const route = useRoute()
const router = useRouter()
const { realNameMap } = useWalletState()
const { getRealNameFromUserInfoByFiatCurrencyId } = useCurrencyData()
const showSheet = ref(false)
const formRef = ref()
const selectedBank = ref()
const appStore = useAppStore()
const setDefault = ref(false)
const isEdit = ref(false)
const showWithdrawMethodSheet = ref(false)
const country = ref()
const transfer = useTransferStore()
// const { runMemberAuthConfig } = useAuthConfig()
/** 首次加载不展示子组件loading */
const selectedMethod = ref(transfer.data.selectedMethod)
const withdrawMethods = ref(transfer.data.withdrawMethods)
const currency_id = ref(transfer.data.currency_id)
/** 巴西货币使用pix */
const isPix = computed(() => {
    return currency_id.value === '702'
})
const accountLabel = computed(() => {
    if(isPix.value) {
        return t('pix_account')
    }
    if(selectedMethod.value?.value === 1){
        return t('bank_account')
    }else if(selectedMethod.value?.value === 2){
        return t('alipay_account')
    }else {
        return t('wallet_account')
    }
})

const bankLabel = computed(() => {
    if(isPix.value) {
        return t('pix_type')
    }
    if(selectedMethod.value?.value === 1){
        return t('choose_bank')
    }else if(selectedMethod.value?.value === 2){
        return ''
    }else {
        return t('choose_wallet')
    }
})


// 需要显示开户网点
const isNeedAddress = computed(() => {
  // 人民币
  return currency_id.value === '701' && selectedMethod.value?.type === 1
})

const schema = computed(() => yup.object().shape({
    method: yup.string().required(t('withdraw_method')),
    address: isNeedAddress.value ? yup.string().required(t('recharge_target_account_address')) : yup.string(),
    password: yup.string().required(t('money_password_placeholder')),
    bank_account: yup.string().required(accountLabel.value),
    real_name: yup.string().required(t('real_name')).min(2),
    bank_name: yup.string().required(t('choose_bank')),
    cfp: yup.string()
}));

const { resetForm, setFieldValue, values, setFieldTouched } = useForm({
  validationSchema: schema,
  initialValues: {
    address: '',
    password: '',
    bank_account: '',
    real_name: getRealNameFromUserInfoByFiatCurrencyId(currency_id.value) ?? realNameMap.value[currency_id.value],
    bank_name: '',
    method: transfer.data.selectedMethod.value,
  }
})

// #region 国家和银行数据
const { data: countryList, runAsync: runGetBankCard } = useRequest(ApiMemberBankcardBank)

/** 新增银行卡 */
const {
  run: runBankcardInsert,
  loading: bankcardInsertLoading,
} = useRequest(ApiMemberBankcardInsert, {
  onSuccess() {
    appStore.updateUserInfo()
    message.success(t('bind_success'))
    router.back()
  },
})
/** 编辑银行卡 */
const {
  runAsync: runUpdateBankcard,
  loading: updateBankcardLoading,
} = useRequest(ApiMemberBankcardUpdate, {
  onSuccess() {
    message.success(t('edit_success'))
    router.back()
  },
})

const countryOptions = computed(() => {
  if (!countryList.value)
    return []
  return countryList.value.map((item) => {
    const temp = {
      label: item.country_name ? item.country_name : '--',
      value: item.country_id,
    }
    return temp
  })
})
const bank_nameOptions = computed(() => {
  if (!country.value)
    return []

  const temp = countryList.value?.find(item => item.country_id === country.value)
  return (temp?.bank_list ?? []).filter(a => !route.query.needDisabledBankIds?.includes(a.id)).map((item) => {
    const temp = {
      icon: `/webp/bank/${item.id}.webp`,
      label: item.name,
      value: item.name,
      id: item.id,
    }
    return temp
  })
})
// 默认选中第一个国家
watch(countryOptions, (val) => {
  if (val.length && !isEdit.value)
    country.value = val[0].value
})

function onSubmit() {
  const { values } = formRef.value
    if (!isEdit.value) {
    // 新增
    runBankcardInsert({
      currency_id: currency_id.value,
      open_name: values.real_name,
      bank_name: selectedBank.value?.label,
      bank_account: values.bank_account,
      is_default: setDefault.value ? 1 : 2,
      pay_password: values.password,
      country: country.value,
      bank_area_cpf: values.cfp,
      city: '',
      address: values.address,
      auth_type: 2,
      bank_id: +(bank_nameOptions.value.find(item => item.value === selectedBank.value?.label)?.id ?? 0),
      type_id: selectedMethod.value.id,
    })
  }
  else {
    // 编辑
    runUpdateBankcard({
      ...selectedBank.value,
      currency_id: currency_id.value,
      bank_name: selectedBank.value?.label,
      bank_account: values.bank_account,
      is_default: setDefault.value ? 1 : 2,
      pay_password: values.password,
      bank_area_cpf: values.cfp,
      country: country.value,
      city: '',
      address: values.address,
      auth_type: 2,
      bank_id: +(bank_nameOptions.value.find(item => item.value === selectedBank.value?.label)?.id ?? 0),
    })
  }
}

watch(selectedMethod, () => runGetBankCard({ currency_id: currency_id.value, type_id: `${selectedMethod.value.value}` }))

await application.allSettled([runGetBankCard({ currency_id: currency_id.value, type_id: `${selectedMethod.value.type}` })])

</script>

<template>
  <div class="m-[1rem] p-[1rem] rounded-[.5rem] bg-bg-black-4 mb-[3.75rem]">
    <Form :validation-schema="schema" @submit="onSubmit" ref="formRef">
        <BaseInput required :disabled="!!values.real_name" :label="t('real_name')" name="real_name" :placeholder="t('real_name_placeholder')" :modelValue="values.real_name"></BaseInput>
        <BaseSheetSelect
            name="method"
            :options="withdrawMethods"
            v-model="values.method"
            :label="t('withdraw_method')"
            :title="t('withdraw_method')"
            @change="val => {selectedMethod = val; selectedBank = ''; setFieldValue('bank_name', '', true)}"
            class="mt-[1rem]"
            required
            >
            <template v-slot:left-icon v-if="withdrawMethods?.length && selectedMethod">
                <BaseImage width="1.125rem" height="1.125rem" :url="selectedMethod.icon" is-network/>
            </template>
            <template #sheet-content="{ item }">
                <li
                    class="mx-[0.875rem] h-[2.5rem] px-[0.5rem] rounded-[0.375rem] flex items-center justify-between"
                    :class="[(item.value === selectedMethod?.value && 'bg-bg-black-4')]"
                >
                    <div class="flex items-center gap-[.1875rem]">
                    <!-- 货币图标 -->
                    <BaseImage width="1.125rem" height="1.125rem" :url="item.icon" is-network/>
                    <span class="font-medium text-text-white-1 text-[1rem] ml-[.5rem]">{{ item.currency_name || item.label }}</span>
                    </div>
                    <div class="size-[1rem] border-[.1875rem] border-brand rounded-[50%]" v-if="item.value === selectedMethod.value"></div>
                </li>
            </template>
        </BaseSheetSelect>
        <BaseSheetSelect
            name="bank_name"
            :options="bank_nameOptions"
            v-model="values.bank_name"
            :placeholder="bankLabel"
            :label="bankLabel"
            :title="t('bind_bank_card')"
            @change="val => selectedBank = val"
            class="mt-[1rem]"
            required
            >
            <template v-slot:left-icon v-if="bank_nameOptions?.length && selectedBank">
                <BaseImage width="1.125rem" height="1.125rem" :url="selectedBank?.icon" is-network/>
            </template>
            <template #sheet-content="{ item }">
                <li
                    class="mx-[0.875rem] h-[2.5rem] px-[0.5rem] rounded-[0.375rem] flex items-center justify-between"
                    :class="[(item.value === selectedBank?.value && 'bg-bg-black-4')]"
                >
                    <div class="flex items-center gap-[.1875rem]">
                    <!-- 货币图标 -->
                    <BaseImage width="1.125rem" height="1.125rem" :url="item.icon" is-network/>
                    <span class="font-medium text-text-white-1 text-[1rem] ml-[.5rem]">{{ item.currency_name || item.label }}</span>
                    </div>
                    <div class="size-[1rem] border-[.1875rem] border-brand rounded-[50%]" v-if="item.value === selectedBank?.value"></div>
                </li>
            </template>
        </BaseSheetSelect>
        <BaseInput required class="mt-[1rem]" :label="t('recharge_target_account_address')" name="address" :placeholder="t('recharge_target_account_address')" v-if="isNeedAddress">
        </BaseInput>
        <BaseInput required class="mt-[1rem]" :label="accountLabel" name="bank_account" :placeholder="accountLabel" input-mode="numeric">
        </BaseInput>
        <BaseInput required class="mt-[1rem]" label="CFP" name="cfp" placeholder="CFP" input-mode="numeric" v-if="isPix">
        </BaseInput>
        <BaseInput required class="mt-[1rem]" :label="t('money_password')" name="password" type="password" :placeholder="t('money_password_placeholder')">
        </BaseInput>
        <BaseCheckbox :checked="setDefault" @click="setDefault = !setDefault" :label="t('set_as_default_card')" class="mt-[.75rem] mb-[1rem]"/>
        <AppRechargeTip :text="t('withdraw_tip')"/>
        <BaseButton class="w-full h-[2.5rem] mt-[1rem]" html-type="submit">
            <span class="text-text-black-10 text-[.75rem] mr-[.25rem]">{{t('bind_withdraw_account_confirm')}}</span>
        </BaseButton>
    </Form>
  </div>
</template>

<style lang="scss"></style>
